<?php declare(strict_types=1);

namespace App\Api\V2\Controller\Withhold\TL;


use App\Http\Controllers\Controller;
use App\Services\Withhold\TL\BillLogService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TLAPIController extends Controller
{
    //通联代扣V2
    public function order(string $day, string $inst_no, string $key_sign, string $inst_no_day)
    {
        try {
            Log::channel("withhold")->info("通联代扣文件请求", [
                "param" => "day=" . $day . "&=" . $inst_no,
            ]);
            $allinpay_configs = Db::table('allinpay_configs')->where(['institution_number' => $inst_no])->first();
            $secret_key = isset($allinpay_configs->secret_key) ? $allinpay_configs->secret_key : ''; // key
//        String key_sign = MD5.encode(day=日期值&inst_no=机构号值&key=机构密钥值);
            $sign = strtolower(md5("day=" . $day . "&inst_no=" . $inst_no . "&key=" . $secret_key));
            Log::channel("withhold")->info("通联代扣", [
                "sign" => $sign
            ]);
            if ($sign != $key_sign) {
                //签名异常
                throw new \Exception("签名计算异常");
            }
            //获取账单数据
            $filePath = storage_path(config("withhold.tl.file_path") . '/' . $inst_no_day . ".txt");
            if (!file_exists($filePath)) {
                //制作文件
                throw new \Exception("文件不存在");
            }
            return response()->download($filePath, $inst_no_day . ".txt");
        } catch (\Exception $e) {
            $errorMsg = $e->getMessage() . "-" . $e->getFile() . "-" . $e->getLine();
            Log::channel("withhold")->info("通联代扣文件", [
                "param" => "day=" . $day . "&=" . $inst_no . "&key=" . $secret_key,
                "error" => $errorMsg
            ]);
            return response()->json(json_encode(["error" => $errorMsg]));
        }
    }

}